package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XinDaiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 安易融  双授权
 */
@Service
public class XinDaiApiBPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", mobileMd5);
        paramMap.put("sex",memberSourceInfo.getSex()==1? 1:0);
        paramMap.put("nameMd5", getMD5(memberSourceInfo.getRealname()));
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",Long.valueOf(memberSourceInfo.getCityCode()));
        paramMap.put("socialSecurity", XinDaiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());



        log.info("【信贷半流程】撞库开始【queryUrl】{}【paramMap】{} ", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【信贷半流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        Boolean data = resultObject.getBoolean("data");
        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);

        if (code == 200 && data) {
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setOutOrderNo(mobileMd5);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setPushSuccess(true);
            extJson.put("outOrderNo",mobileMd5);
            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = resultObject.getBigDecimal("price");
                if(price == null || price.compareTo(new BigDecimal(0.00))== -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = typeRate.multiply(price);
                pushApiResult.setPrice(price);
                pushApiResult.setPriceRight(priceRight);
            }
            return pushApiResult;
        }
        return pushApiResult;
    }

    private Object getMD5(String realName) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(realName.getBytes());
            byte[] digest = md.digest();
            BigInteger no = new BigInteger(1, digest);
            String  nameMd5 = no.toString(16);
            return nameMd5;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?1:0);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",Long.valueOf(memberSourceInfo.getCityCode()));
        paramMap.put("socialSecurity", XinDaiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XinDaiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XinDaiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XinDaiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XinDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XinDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XinDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard",XinDaiUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XinDaiUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XinDaiUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 1);
        paramMap.put("loanPurpose",XinDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature",pushApiKeyParam.getApiCode());


        log.info("【信贷半流程】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【信贷半流程】导单结束【result】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        JSONObject data = resultObject.getJSONObject("data");
        Boolean state = data.getBoolean("state");

        if (code == 200 && state) {
            String url = data.getString("url");
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
       return  null;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        JSONObject jsonObject = JSON.parseObject(paramContent);
        Boolean state = jsonObject.getBoolean("state");
        noticeParamDTO.setSettleFlag(state);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }

        String md5Phone = jsonObject.getString("phoneMd5");
        noticeParamDTO.setOrderNo(md5Phone);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId,md5Phone);

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
